<template>
  <el-cascader
    :props="deptProps"
    :show-all-levels="false"
    clearable
    filterable
    :placeholder="placeholder"
    ref="CascaderRef"
    style="width: 100%"
    :disabled="disabled"
    v-model="inputValue"
    :options="cascaderData"
    @visible-change="visibleChange"
  >
    <template #empty>
      <div v-if="isLoading" class="loading-dept">
        <div>拼命加载中</div>
        <el-icon class="is-loading"> <Loading /> </el-icon>
      </div>
    </template>
  </el-cascader>
</template>
<script lang="ts" setup>
import { ref, watch, inject, onBeforeMount } from "vue";
import { Loading } from "@element-plus/icons-vue";
const $request: any = inject("$request");
const props = defineProps({
  value: {
    type: [String, Number],
    default: "",
  },
  placeholder: {
    type: String,
    required: false,
    default: "请选择所属机构",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const deptProps = {
  value: "deptId",
  label: "deptName",
  children: "children",
  checkStrictly: true,
  expandTrigger: "click",
  emitPath: false,
};
const inputValue = ref(props.value);
const IsshowPopper = ref(false);
const isLoading = ref(false);
const cascaderData = ref([]);
const CascaderRef = ref<any>(null);
watch(
  inputValue,
  (New, Old) => {
    if (IsshowPopper.value) {
      CascaderRef.value.togglePopperVisible();
    }
  },
  { deep: true }
);
/** 方法 */
// 获取机构数据
const getDeaptDatas = () => {
  isLoading.value = true;
  const action = {
    model: {
      name: "",
    },
    offset: 0,
    limit: 10000,
  };
  $request
    .rpc({ name: "protect.dept.PageDepts", action })
    .then((result: any) => {
      cascaderData.value = result.list.data;
      setTimeout(() => {
        isLoading.value = false;
      }, 500);
    })
    .catch(() => {
      isLoading.value = false;
    });
};
// 下拉框出现/隐藏时触发
const visibleChange = (e: any) => {
  IsshowPopper.value = e;
};
/** 生命周期钩子 */
onBeforeMount(() => {
  getDeaptDatas();
});
</script>

<style lang="scss" scoped>
.loading-dept {
  text-align: center;
  .el-icon.is-loading {
    margin-top: 20px;
    font-size: 30px;
    color: var(--theme-primary);
  }
}
</style>